/**
 * 
 */
package com.agilegroup.crm.ui;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import roboguice.inject.InjectView;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.view.MenuItem;
import com.agilegroup.crm.AgileApplication;
import com.agilegroup.crm.R;
import com.agilegroup.crm.adapters.SpinnerAdapter;
import com.agilegroup.crm.model.Appointment;
import com.agilegroup.crm.model.AppointmentDetails;
import com.agilegroup.crm.model.AppointmentDetailsList;
import com.agilegroup.crm.requests.NewAppointmentDetailsJsonRequest;
import com.agilegroup.crm.requests.NewAppointmentJsonRequest;
import com.agilegroup.crm.ui.actions.DateTimeDialog;
import com.agilegroup.crm.ui.fragments.ConnectionDialogFragment;
import com.agilegroup.crm.utils.OnlineChecker;
import com.agilegroup.crm.utils.SessionManager;
import com.agilegroup.crm.utils.Validation;
import com.octo.android.robospice.persistence.DurationInMillis;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;

/**
 * @author hisham
 *
 */
public class NewAppointmentActivity extends BaseActivity {
	
	@InjectView(R.id.lblAppointmentOwner)
	TextView lblAppointmentOwner;
	@InjectView(R.id.spinnerSalesMan)
	Spinner spinnerSalesMan;
	@InjectView(R.id.spinnerContactedPerson)
	Spinner spinnerContactedPerson;
	@InjectView(R.id.txtDate) 
	EditText txtDate;
	@InjectView(R.id.txtStartTime)
	EditText txtStartTime;
	@InjectView(R.id.txtEndTime)
	EditText txtEndTime;
	@InjectView(R.id.lblDay)
	TextView lblDay;
	@InjectView(R.id.txtComment)
	TextView txtComment;
	@InjectView(R.id.radioinConfirmationDateExpected)
	RadioGroup radioinConfirmationDateExpected;
	@InjectView(R.id.radioMeetingdone)
	RadioGroup radioMeetingdone;
	@InjectView(R.id.txtCustomerNeed)
	TextView txtCustomerNeed;
	@InjectView(R.id.radioDemodone)
	RadioGroup radioDemodone;
	@InjectView(R.id.radioOfferSubmitted)
	RadioGroup radioOfferSubmitted;
	@InjectView(R.id.radioDiscountdone)
	RadioGroup radioDiscountdone;
	@InjectView(R.id.radioCompetitorOffer)
	RadioGroup radioCompetitorOffer;
	@InjectView(R.id.txtReplyPeriod)
	TextView txtReplyPeriod;
	@InjectView(R.id.radioDealClosingdone)
	RadioGroup radioDealClosingdone;
	@InjectView(R.id.txtNextFollowUpDate)
	EditText txtNextFollowUpDate;
	@InjectView(R.id.radioinNextFollowUp)
	RadioGroup radioinNextFollowUp;
	@InjectView(R.id.spinnerNextFollowUpType)
	Spinner spinnerNextFollowUpType;
	@InjectView(R.id.txtNextFollowUpDetails)
	EditText txtNextFollowUpDetails;
	
	private RadioButton SelectedRadioConfirmationDateExcepted;
	private RadioButton SelectedRadioMeetingDone;
	private RadioButton SelectedRadioDemoDone;
	
	private RadioButton SelectedRadioOfferSubmitted;
	private RadioButton SelectedRadioDiscountDone;
	private RadioButton SelectedRadioCompetitorOffer;
	private RadioButton SelectedRadioDealClosingDone;
	private RadioButton SelectedRadioNextFollowUp;
	
	private int hour;
	private int minute;
	private int year;
	private int month;
	private int day;
	
	private SessionManager sessionManager;
	private static final String JSON_CACHE_KEY = "new_appointment_get_json";
	private static final int START_TIME_DIALOG_ID = 1;
	private static final int END_TIME_DIALOG_ID = 2;
	private static final int DATE_DIALOG_ID = 3;
	private static final int FOLLOW_DATE_DIALOG_ID = 4;
	
	private String leadId;
	
	@SuppressWarnings("static-access")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.new_appointment);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		
		Intent intent = getIntent();
		leadId  = intent.getStringExtra("leadId");
        Log.d("leaId From newCall", leadId);
        
        sessionManager = new SessionManager(getBaseContext());    
    	HashMap<String, String> user = sessionManager.getUserDetails();
    	String empId = user.get(sessionManager.KEY_ID);
    	AgileApplication.getInstance().spiceManager.execute(new NewAppointmentDetailsJsonRequest(empId),JSON_CACHE_KEY,DurationInMillis.ALWAYS_EXPIRED,new AppointmentDetailsListJsonRequestListener());
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	protected Dialog onCreateDialog(int id) {
		final Calendar c = Calendar.getInstance();
         year = c.get(Calendar.YEAR);
         month = c.get(Calendar.MONTH);
         day = c.get(Calendar.DAY_OF_MONTH);
         hour = c.get(Calendar.HOUR_OF_DAY);
 		 minute = c.get(Calendar.MINUTE);
 		
		if(START_TIME_DIALOG_ID==id){
			return new TimePickerDialog(this,new DateTimeDialog(txtStartTime,null).timePickerListener, hour, minute,false);
		}
		else if(END_TIME_DIALOG_ID==id){
			
			return new TimePickerDialog(this,new DateTimeDialog(txtEndTime,null).timePickerListener, hour, minute,false);
		}
		if(DATE_DIALOG_ID==id){
			 DatePickerDialog dialog =  new DatePickerDialog(this, new DateTimeDialog(txtDate,lblDay).datePickerListener,year, month,day);
		        dialog.setTitle("Set Date");
		        int sdkVersion = android.os.Build.VERSION.SDK_INT;
		        if(sdkVersion>=android.os.Build.VERSION_CODES.HONEYCOMB){
		        	dialog.getDatePicker().setCalendarViewShown(false);
		        }
		        
		        return dialog;
		}
		else if(FOLLOW_DATE_DIALOG_ID==id){
			 DatePickerDialog dialog =  new DatePickerDialog(this, new DateTimeDialog(txtNextFollowUpDate,null).datePickerListener,year, month,day);
		        dialog.setTitle("Set Date");
		        int sdkVersion = android.os.Build.VERSION.SDK_INT;
		        if(sdkVersion>=android.os.Build.VERSION_CODES.HONEYCOMB){
		        	dialog.getDatePicker().setCalendarViewShown(false);
		        }
		        
		        return dialog;
		}
		return null;
	}
	@SuppressWarnings("deprecation")
	public void showDatePickerDialog(View v) {
//		SherlockDialogFragment newFragment = new DatePickerFragment(txtDate,lblDay);
//	    newFragment.show(getSupportFragmentManager(), "datePicker");
		showDialog(DATE_DIALOG_ID);
	}
	@SuppressWarnings("deprecation")
	public void showNextFollowUpDatePickerDialog(View v) {
//		SherlockDialogFragment newFragment = new DatePickerFragment(txtNextFollowUpDate,null);
//	    newFragment.show(getSupportFragmentManager(), "datePicker");
		showDialog(FOLLOW_DATE_DIALOG_ID);
	}
	
	@SuppressWarnings("deprecation")
	public void showTimePickerDialogForStartTime(View v) {
//		SherlockDialogFragment newFragment = new TimePickerFragment(txtStartTime);
//	    newFragment.show(getSupportFragmentManager(), "timePicker");
		showDialog(START_TIME_DIALOG_ID);
	}
	@SuppressWarnings("deprecation")
	public void showTimePickerDialogForEndTime(View v) {
//		SherlockDialogFragment newFragment = new TimePickerFragment(txtEndTime);
//	    newFragment.show(getSupportFragmentManager(), "timePicker");
		showDialog(END_TIME_DIALOG_ID);
	}
	@SuppressLint("SimpleDateFormat")
	public void addAppointment(View v){
		Validation validation = new Validation(this);
		
		boolean isDateNull = validation.isTextFieldNull(txtDate,R.string.message_date_required);
		boolean isStartTimeNull = validation.isTextFieldNull(txtStartTime,R.string.message_start_time_required);
		boolean isEndTimeNull = validation.isTextFieldNull(txtEndTime,R.string.message_end_time_required);
		List<String> list = new ArrayList<String>();
		StringBuilder builder = new StringBuilder();
		if(isDateNull==false||isStartTimeNull==false||isEndTimeNull==false){
			if(isDateNull==false){
				list.add(getResources().getString(R.string.message_date_required));
			}
			if(isStartTimeNull==false){
				list.add(getResources().getString(R.string.message_start_time_required));
			}
			if(isEndTimeNull==false){
				list.add(getResources().getString(R.string.message_end_time_required));
			}
			if(isStartTimeNull!=false && isEndTimeNull!=false){
				boolean isTimeValid = validation.isTimeValid(txtStartTime, txtEndTime,R.string.message_time_valid);
				if(isTimeValid==false){
					list.add(getResources().getString(R.string.message_time_valid));
				}
			}
			if(txtNextFollowUpDate.getText().length()!=0 && txtDate.getText().length()!=0){
				boolean isDateValid = validation.
						isDateValid(txtDate,txtNextFollowUpDate,R.string.message_follow_date_required);
					if(isDateValid==false){
						list.add(getResources().getString(R.string.message_follow_date_required));
					}
			}
			for(String i : list)
			{
			     builder.append(i + "\n");
			}
			Toast.makeText(this, builder, Toast.LENGTH_LONG).show();
		}
		 else {
			boolean isTimeValid = validation.isTimeValid(txtStartTime, txtEndTime,R.string.message_time_valid);
            DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    		Date date=null;
    		Date followUpDate=null;
    		Appointment appointment = new Appointment();
    		
    		com.agilegroup.crm.model.Spinner salesMan;
    		com.agilegroup.crm.model.Spinner contactedPerson;
    		if(!(spinnerSalesMan.getSelectedItem() == null)){
    			salesMan = (com.agilegroup.crm.model.Spinner)spinnerSalesMan.getSelectedItem();
    			appointment.setSalesManId(Integer.parseInt(salesMan.getId()));
            }
    		if(!(spinnerContactedPerson.getSelectedItem() == null)){
    		 contactedPerson = (com.agilegroup.crm.model.Spinner)spinnerContactedPerson.getSelectedItem();
    		 appointment.setContactedPersonId(Integer.parseInt(contactedPerson.getId()));
           }
    		appointment.setSalesManId(1);
    		appointment.setContactedPersonId(1);
    		if(txtDate.getText()!=null){
    			try {
    				date = format.parse(txtDate.getText().toString());
    				appointment.setDate(date);
    			} catch (ParseException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			
    		}
    		if(lblDay.getText()!=null){
    			appointment.setDay(lblDay.getText().toString());
    		}
    		if(txtStartTime.getText()!=null){
    			appointment.setTime(txtStartTime.getText().toString());
    		}
    		if(txtEndTime.getText()!=null){
    			appointment.setMeetingDuration(txtEndTime.getText().toString());
    		}
    		if(txtComment.getText()!=null){
    			appointment.setComment(txtComment.getText().toString());
    		}
    		Integer selectedId = radioinConfirmationDateExpected.getCheckedRadioButtonId();
    		SelectedRadioConfirmationDateExcepted = (RadioButton)findViewById(selectedId);
    		if(SelectedRadioConfirmationDateExcepted!=null){
    			if(SelectedRadioConfirmationDateExcepted.getText().equals("Yes")){
    				appointment.setConfirmationDateExpected("true");
    			}
    			else{
    				appointment.setConfirmationDateExpected("false");
    			}
    		}
    		Integer selectedMeetingDoneId = radioMeetingdone.getCheckedRadioButtonId();
    		SelectedRadioMeetingDone = (RadioButton)findViewById(selectedMeetingDoneId);
    		if(SelectedRadioMeetingDone!=null){
    			if(SelectedRadioMeetingDone.getText().equals("Yes")){
    				appointment.setMeetingDone(true);
    			}
    			else{
    				appointment.setMeetingDone(false);
    			}
    		}
    		Integer selectedDemoDoneId = radioDemodone.getCheckedRadioButtonId();
    		SelectedRadioDemoDone = (RadioButton)findViewById(selectedDemoDoneId);
    		if(SelectedRadioDemoDone!=null){
    			if(SelectedRadioDemoDone.getText().equals("Yes")){
    				appointment.setDemoDone(true);
    			}
    			else{
    				appointment.setDemoDone(false);
    			}
    		}
    		Integer selectedofferSubmittedId = radioOfferSubmitted.getCheckedRadioButtonId();
    		SelectedRadioOfferSubmitted = (RadioButton)findViewById(selectedofferSubmittedId);
    		if(SelectedRadioOfferSubmitted!=null){
    			if(SelectedRadioOfferSubmitted.getText().equals("Yes")){
    				appointment.setOfferSubmitted(true);
    			}
    			else{
    				appointment.setOfferSubmitted(false);
    			}
    		}
    		Integer selectedDiscountDoneId = radioDiscountdone.getCheckedRadioButtonId();
    		SelectedRadioDiscountDone = (RadioButton)findViewById(selectedDiscountDoneId);
    		if(SelectedRadioDiscountDone!=null){
    			if(SelectedRadioDiscountDone.getText().equals("Yes")){
    				appointment.setDiscountDone(true);
    			}
    			else{
    				appointment.setDiscountDone(false);
    			}
    		}
    		Integer selectedCompetitorOfferId = radioCompetitorOffer.getCheckedRadioButtonId();
    		SelectedRadioCompetitorOffer = (RadioButton)findViewById(selectedCompetitorOfferId);
    		if(SelectedRadioCompetitorOffer!=null){
    			if(SelectedRadioCompetitorOffer.getText().equals("Yes")){
    				appointment.setCompatitorOffer(true);
    			}
    			else{
    				appointment.setCompatitorOffer(false);
    			}
    		}
    		if(txtReplyPeriod.getText()!=null){
    			appointment.setReplyPeriod(txtReplyPeriod.getText().toString());
    		}
    		Integer selectedDealClosingDoneId = radioDealClosingdone.getCheckedRadioButtonId();
    		SelectedRadioDealClosingDone = (RadioButton)findViewById(selectedDealClosingDoneId);
    		if(SelectedRadioDealClosingDone!=null){
    			if(SelectedRadioDealClosingDone.getText().equals("Yes")){
    				appointment.setDealClosingDone(true);
    			}
    			else{
    				appointment.setDealClosingDone(false);
    			}
    		}
    		
    		Integer selectedNextFollowUp = radioinNextFollowUp.getCheckedRadioButtonId();
    		SelectedRadioNextFollowUp = (RadioButton)findViewById(selectedNextFollowUp);
    		if(SelectedRadioNextFollowUp!=null){
    			if(SelectedRadioNextFollowUp.getText().equals("Yes")){
    				appointment.setNextFollowUp(true);
    			}
    			else{
    				appointment.setNextFollowUp(false);
    			}
    		}	
    		if(String.valueOf(spinnerNextFollowUpType.getSelectedItem()).equals("--none--")){
    			appointment.setFollowUpType("--none--");
    		}
    		if(String.valueOf(spinnerNextFollowUpType.getSelectedItem()).equals("Appointment")){
    			appointment.setFollowUpType("Appointment");
    		}
    		if(String.valueOf(spinnerNextFollowUpType.getSelectedItem()).equals("Call")){
    			appointment.setFollowUpType("Call");
    		}
    		if(txtComment.getText()!=null){
    			appointment.setComment(txtComment.getText().toString());
    		}
    		if(txtNextFollowUpDate.getText()!=null){
    			try {
    				followUpDate = format.parse(txtNextFollowUpDate.getText().toString());
    				appointment.setFollowUpDate(followUpDate);
    			} catch (ParseException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			
    		}
    		if(txtNextFollowUpDetails.getText()!=null){
    			appointment.setFollowUpDetails(txtNextFollowUpDetails.getText().toString());
    		}
    		
    		appointment.setDateCreated(new Date());
    		appointment.setParentType("lead");
    		appointment.setParentId(Integer.parseInt(leadId));
    		List<String> errorList = new ArrayList<String>();
    		StringBuilder stringBuilder = new StringBuilder();
    		if(isTimeValid==false){
    			errorList.add(getResources().getString(R.string.message_time_valid));
    			if(txtNextFollowUpDate.getText().length()!=0){
    				boolean isDateValid = validation.
    						isDateValid(txtDate,txtNextFollowUpDate,R.string.message_follow_date_required);
    				if(isDateValid==false){
    					errorList.add(getResources().getString(R.string.message_follow_date_required));
    				}
    			}
    			for(String i : errorList)
    			{
    				stringBuilder.append(i + "\n");
    			}
    			Toast.makeText(this, getResources().getString(R.string.message_time_valid), Toast.LENGTH_SHORT).show();
    		}
    		else{
 			   OnlineChecker checker = new OnlineChecker(NewAppointmentActivity.this);
 			   if(checker.isOnline()==true){
 				  postNewAppointment(appointment); 
 			   }
 			   else{
 				   SherlockDialogFragment dialogFragment = new ConnectionDialogFragment();
        			   dialogFragment.show(getSupportFragmentManager(), "connectionDialog");
 			   }
 		   }
        }
	}
	public void cancelButton(View v){
		finish();
	}
	public void postNewAppointment(Appointment appointment){
		AgileApplication.getInstance().spiceManager.execute(new NewAppointmentJsonRequest(appointment), new NewAppointmentJsonRequestListener());
		//NewAppointmentTask appointmentTask = new NewAppointmentTask();
		//appointmentTask.execute(appointment);
	}
	
	private class AppointmentDetailsListJsonRequestListener implements RequestListener<AppointmentDetailsList>{

		@Override
		public void onRequestFailure(SpiceException arg0) {
			Toast.makeText(NewAppointmentActivity.this, "Failure", Toast.LENGTH_SHORT).show();
			
		}

		@Override
		public void onRequestSuccess(AppointmentDetailsList appointmentDetailsList) {
			//Toast.makeText(NewCallActivity.this, "Success", Toast.LENGTH_SHORT).show();
			lblAppointmentOwner.setText(appointmentDetailsList.getOwnerName());
			List<AppointmentDetails>appointmentDetails=appointmentDetailsList.getAppointmentDetails();
			List<com.agilegroup.crm.model.Spinner>salesMans = new ArrayList<com.agilegroup.crm.model.Spinner>();
			List<com.agilegroup.crm.model.Spinner>contactedPersons = new ArrayList<com.agilegroup.crm.model.Spinner>();
			for (AppointmentDetails appointmentDetails2 : appointmentDetails) {
				com.agilegroup.crm.model.Spinner salesMan = new com.agilegroup.crm.model.Spinner();
				salesMan.setId(appointmentDetails2.getSalesManId().toString());
				salesMan.setName(appointmentDetails2.getSalesManName());
				salesMans.add(salesMan);
				
				com.agilegroup.crm.model.Spinner contactedPerson = new com.agilegroup.crm.model.Spinner();
				contactedPerson.setId(appointmentDetails2.getContactedPersonId().toString());
				contactedPerson.setName(appointmentDetails2.getContactedPersonName());
				contactedPersons.add(contactedPerson);
			}
			addItemsToSalesMan(salesMans);
			addItemsToContactedPerson(contactedPersons);
		}
		public void addItemsToSalesMan(List<com.agilegroup.crm.model.Spinner>salesMans){
			SpinnerAdapter adapter = new SpinnerAdapter(NewAppointmentActivity.this, R.layout.spinner_row, salesMans);
			spinnerSalesMan.setAdapter(adapter);
		}
		public void addItemsToContactedPerson(List<com.agilegroup.crm.model.Spinner>contactedPersons){
			SpinnerAdapter adapter = new SpinnerAdapter(NewAppointmentActivity.this, R.layout.spinner_row, contactedPersons);
			spinnerContactedPerson.setAdapter(adapter);
		}
	}
	public class NewAppointmentJsonRequestListener implements RequestListener<Appointment>{

		@Override
		public void onRequestFailure(SpiceException arg0) {
			Toast.makeText(NewAppointmentActivity.this, "Failure", Toast.LENGTH_SHORT).show();
			
		}

		@Override
		public void onRequestSuccess(Appointment appointment) {
			if(appointment==null){
				Toast.makeText(NewAppointmentActivity.this, "This Appointment is not Allowed", Toast.LENGTH_SHORT).show();
			}
			else{
				Toast.makeText(NewAppointmentActivity.this, getResources().getString(R.string.message_appointment_post_sucess), Toast.LENGTH_SHORT).show();
				finish();
			}
		}
		
	}
	@Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
    	int itemId = item.getItemId();
        switch (itemId) {
        case android.R.id.home:
             finish();
            break;

        }

        return true;
    }
}
